package com.shyroke.daydayzhuanweb.controller;

import com.google.gson.Gson;
import com.shyroke.daydayzhuansvc.util.ExceptionUtil;
import com.shyroke.daydayzhuansvc.util.WebUtilPro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * BaseController
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2017年4月4日
 */
public abstract class BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 登录认证异常
     */
    @ExceptionHandler({ UnauthenticatedException.class, AuthenticationException.class })
    public String authenticationException(HttpServletRequest request, HttpServletResponse response) {
        if (WebUtilPro.isAjaxRequest(request)) {
            // 输出JSON
            Map<String,Object> map = new HashMap<>();
            map.put("code", "-999");
            map.put("message", "未登录");
            writeJson(map, response);
            return null;
        } else {
            return "redirect:/system/login";
        }
    }

    /**
     * 权限异常
     */
    @ExceptionHandler({ AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            Gson gson = new Gson();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            out = response.getWriter();
            StringBuffer hmtlBuffer = new StringBuffer();
            hmtlBuffer.append("  <link rel=\"stylesheet\" href=\"/layui/css/layui.css\">");
            hmtlBuffer.append("  <script src=\"/script/jquery-3.3.1.min.js\"></script>");
            hmtlBuffer.append("  <script src=\"/layui/layui2.js\"></script>");
            hmtlBuffer.append(" <script>");
            hmtlBuffer.append("  layui.use(['layer','form'],function () { ");
            hmtlBuffer.append(" layer.msg(\"该用户没有权限操作！\");");
            hmtlBuffer.append("   });");


            out.write(hmtlBuffer.toString());
        } catch (IOException e) {
            logger.info(ExceptionUtil.getMessage(e));
        } finally {
            if (out != null) {
                out.close();
            }
        }

        return null;
    }

    /**
     * 输出JSON
     *
     * @param response
     * @author SHANHY
     * @create 2017年4月4日
     */
    private void writeJson(Map<String,Object> map, HttpServletResponse response) {

    }
}